 package be.kuleuven.cs.mume.actions;

import org.mt4j.components.MTComponent;
import org.mt4j.components.visibleComponents.shapes.AbstractShape;
import org.mt4j.components.visibleComponents.shapes.MTLine;
import org.mt4j.sceneManagement.AbstractScene;
import org.mt4j.sceneManagement.IPreDrawAction;
import org.mt4j.sceneManagement.Iscene;
import org.mt4j.util.math.Vertex;

import be.kuleuven.cs.mume.objects.MediaObject;
import be.kuleuven.cs.mume.objects.PhysicsRoundedRectangle;

public class UpdateConnLine implements IPreDrawAction {
	
	private AbstractShape object1;
	private AbstractShape object2;
	private MTLine connectLine;
	private MTComponent container;
	private boolean wasRemoved = false;
	
	public UpdateConnLine(AbstractShape object1, AbstractShape object2, MTLine connectLine, MTComponent container) {
		this.object1 = object1;
		this.object2 = object2;
		this.connectLine = connectLine;
		this.container = container;
	}

	public boolean isLoop() {
		// TODO Auto-generated method stub
		return true;
	}

	public void processAction() {
		updateLine(connectLine,object1.getCenterPointGlobal().x,object1.getCenterPointGlobal().y,object2.getCenterPointGlobal().x,object2.getCenterPointGlobal().y);
	}
	
	private void updateLine(MTLine line, float startX, float startY, float endX, float endY) {
		Vertex[] lineVertices = line.getVerticesGlobal();

		lineVertices[0].x = startX;
		lineVertices[0].y = startY;
		lineVertices[1].x = endX;
		lineVertices[1].y = endY;
		boolean removed = false;
		double dist = Math.sqrt((startX-endX)*(startX-endX)+(startY-endY)*(startY-endY));
		MTComponent o2 =  object2.getParent();
		if(o2 instanceof PhysicsRoundedRectangle){
			PhysicsRoundedRectangle r = (PhysicsRoundedRectangle) o2;
			if (r.isRemoved()) {
				if (dist > 3000) {
					r.destroyBody();
					r.removeFromParent();
				}
				removed |= true;
//				mscene.unregisterPreDrawAction(this);
			}
		}
		MTComponent o1 =  object1.getParent();
		if(o1 instanceof PhysicsRoundedRectangle){
			PhysicsRoundedRectangle r = (PhysicsRoundedRectangle) o1;
			if (r.isRemoved()) {
				if (dist > 3000) {
					r.destroyBody();
					r.removeFromParent();
				}
				removed |= true;
			}
		}
		wasRemoved |= removed;
		if(removed){
			container.removeChild(line);
		}else{
			if(wasRemoved)
				container.addChild(line);
		}
		wasRemoved = removed;

		line.setVertices(lineVertices);
	}

}
